import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { createFromIconfontCN } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Modal, Input, InputNumber, Row, Col, Button,
} from 'antd';
import { FormComponentProps } from '@ant-design/compatible/es/form';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1430304_y2xsdrlvrh.js',
});

interface RechargeInfoProps extends FormComponentProps {
  visible: boolean;
  formValues: {
    fcs_id: number,
    fcs_name: string,
  };
  fetchAction: (typeName: string, params: any) => void;
  changeModal: (visible: boolean) => void;
  withdrawalInfo?: any;
  withdrawalState?: boolean;
  subLoading?: boolean;
}

interface RechargeInfoState {
  withdrawalInfo: {
    fcs_id: number | string,
    fcs_name: string,
    phone: string,
    day_max_quota: number,
    withdraw_amount: number,
    income: number,
    withdraw_charge_ratio: number,
  };
  per_withdrawalInfo: any;
  submitLoading: boolean;
  poundage: number | string;
  countdown: number;
}

function mapStateToProps(state: any) {
  const {
    withdrawalMoney: {
      withdrawalInfo,
      withdrawalState,
      subLoading,
    },
  } = state;

  return {
    withdrawalInfo,
    withdrawalState,
    subLoading,
  };
}

@connect(mapStateToProps)

class RechargeInfoElem extends Component<RechargeInfoProps, RechargeInfoState> {
  state: RechargeInfoState = {
    withdrawalInfo: {
      fcs_id: '',
      fcs_name: '',
      phone: '',
      day_max_quota: 0,
      withdraw_amount: 0,
      income: 0,
      withdraw_charge_ratio: 0,
    },
    per_withdrawalInfo: {},
    submitLoading: false,
    poundage: '0.00',
    countdown: 0,
  }

  interval: any = null;

  timeout: any = null;

  static getDerivedStateFromProps(nextProps: RechargeInfoProps, perState: RechargeInfoState) {
    const {
      withdrawalInfo,
      withdrawalState,
      changeModal,
      visible,
      subLoading,
    } = nextProps;
    const { per_withdrawalInfo } = perState;
    if (withdrawalInfo
      && withdrawalInfo.withdrawalResults
      && !Object.is(withdrawalInfo, per_withdrawalInfo)
    ) {
      return ({
        withdrawalInfo,
        per_withdrawalInfo: withdrawalInfo,
      });
    }

    if (withdrawalState && visible) {
      changeModal(false);
      return ({
        submitLoading: false,
        withdrawalInfo: {
          fcs_id: '',
          fcs_name: '',
          phone: '',
          day_max_quota: 0,
          withdraw_amount: 0,
          income: 0,
          withdraw_charge_ratio: 0,
        },
      });
    }

    if (subLoading && visible) {
      return ({
        submitLoading: false,
      });
    }
    return null;
  }


  handleChangeMoney = (value: any) => {
    const { withdrawalInfo: { withdraw_charge_ratio } } = this.state;
    this.setState({
      poundage: (value * (withdraw_charge_ratio / 1000)).toFixed(4),
    });
  }

  handleAll = () => {
    const { withdrawalInfo } = this.state;

    const {
      income,
      day_max_quota,
      withdraw_amount,
      withdraw_charge_ratio,
    } = withdrawalInfo;

    const { form: { setFieldsValue } } = this.props;

    const amount = (income / 100).toFixed(2);

    const max_withdrwa_amount = day_max_quota - withdraw_amount;
    let remaining_amount = (
      (max_withdrwa_amount - max_withdrwa_amount * withdraw_charge_ratio / 1000) / 100
    ).toFixed(2);

    if (amount < remaining_amount) {
      remaining_amount = amount;
    }

    setFieldsValue({ amount: remaining_amount }, () => {
      this.handleChangeMoney(remaining_amount);
    });
  }

  handleSubmit = () => {
    const { withdrawalInfo: { phone } } = this.state;
    const { formValues, fetchAction, form: { validateFields } } = this.props;

    validateFields((errors, values) => {
      if (!errors) {
        const params = {
          ...formValues,
          ...values,
          phone,
          pay_way: 1,
        };
        this.setState({ submitLoading: true });
        fetchAction('alipay', params);
      }
    });
  }

  handleCancel = () => {
    const { changeModal } = this.props;
    changeModal(false);
    this.setState({
      submitLoading: false,
      withdrawalInfo: {
        fcs_id: '',
        fcs_name: '',
        phone: '',
        day_max_quota: 0,
        withdraw_amount: 0,
        income: 0,
        withdraw_charge_ratio: 0,
      },
    });
  }

  handleCode = () => {
    clearTimeout(this.interval);

    this.interval = setTimeout(() => {
      let { countdown } = this.state;
      countdown = 60;

      this.setState({ countdown }, () => {
        const { withdrawalInfo } = this.state;
        const { fetchAction } = this.props;
        fetchAction('vcode', { phone: withdrawalInfo.phone });
      });

      this.timeout = setInterval(() => {
        countdown -= 1;
        if (countdown < 0) {
          clearInterval(this.timeout);
        } else {
          this.setState({ countdown });
        }
      }, 1000);
    }, 500);
  }

  renderInputInfoElem = () => {
    const { poundage, countdown, withdrawalInfo } = this.state;

    const {
      fcs_name,
      income,
      phone,
      day_max_quota,
      withdraw_amount,
      withdraw_charge_ratio,
    } = withdrawalInfo;

    const { form: { getFieldDecorator } } = this.props;

    const amount = (income / 100).toFixed(2);

    const max_withdrwa_amount = day_max_quota - withdraw_amount;
    let remaining_amount = ((
      max_withdrwa_amount - max_withdrwa_amount * withdraw_charge_ratio / 1000
    ) / 100).toFixed(2);


    if (Number(amount) < Number(remaining_amount)) {
      remaining_amount = amount;
    }

    const day_remaining_amount = (day_max_quota - withdraw_amount) / 100;

    const AlipayIcon = <MyIcon
      type="iconzhifubao"
      style={{
        fontSize: 18,
        position: 'relative',
        top: 6,
        marginRight: 4,
      }}
    />;

    return (
      <Fragment>
        <Col span={16} offset={4}>
          <Form.Item label={AlipayIcon} colon={false} style={{ marginBottom: 0, marginLeft: 88 }}>
            支付宝
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　　　　　合作商" colon={false} style={{ marginBottom: 0 }}>
            {fcs_name}
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　　　　账户余额" colon={false} style={{ marginBottom: 0 }}>
            {amount} 元
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　　　提现手续费" colon={false} style={{ marginBottom: 0 }}>
            {Number(poundage) >= 0 ? poundage : 0} 元
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="当日上限提现额度" colon={false} style={{ marginBottom: 0 }}>
            {(Number(day_max_quota) / 100).toFixed(2)} 元
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="当日剩余提现额度" colon={false} style={{ marginBottom: 4 }}>
            {Number(day_remaining_amount) >= 0 ? day_remaining_amount : 0} 元
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　　　　提现金额" colon={false}>
            <div style={{ display: 'flex', justifyContent: 'center', position: 'relative' }}>
              {getFieldDecorator('amount', {
                rules: [{ required: true, message: '请输入提现金额' }],
              })(
                <InputNumber
                  min={0.1}
                  max={Number(remaining_amount) >= 0 ? Number(remaining_amount) : 0}
                  step={0.1}
                  placeholder="请输入"
                  style={{ width: '100%' }}
                  onChange={this.handleChangeMoney}
                />,
              )}
              <div
                className="operLink"
                onClick={this.handleAll}
                style={{ position: 'absolute', right: -32 }}
              >
                全部
              </div>
            </div>
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　提现手机号验证" colon={false}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <Button disabled style={{ width: 110, padding: 0 }}>{phone}</Button>
              <Button
                disabled={countdown > 0}
                className="marginL8"
                style={{ width: 88, padding: 0, textAlign: 'center' }}
                onClick={this.handleCode}
              >
                {countdown || '获取验证码'}
              </Button>
            </div>
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　　　短信验证码" colon={false}>
            {getFieldDecorator('vcode', {
              rules: [{ required: true, message: '请输入短信验证码' }],
            })(
              <Input
                placeholder="请输入"
                style={{ width: '100%' }}
              />,
            )}
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　　　支付宝账号" colon={false}>
            {getFieldDecorator('pay_account', {
              rules: [{ required: true, message: '请输入支付宝账号' }],
            })(
              <Input placeholder="请输入" style={{ width: '100%' }} />,
            )}
          </Form.Item>
        </Col>
        <Col span={16} offset={4}>
          <Form.Item label="　　　支付宝姓名" colon={false}>
            {getFieldDecorator('real_name', {
              rules: [{ required: true, message: '请输入支付宝姓名' }],
            })(
              <Input placeholder="请输入" style={{ width: '100%' }} />,
            )}
          </Form.Item>
        </Col>
      </Fragment>
    );
  }

  render() {
    const { submitLoading } = this.state;
    const { visible } = this.props;

    return (
      <Modal
        title="提现方式"
        className="withdraw"
        visible={visible}
        centered
        destroyOnClose
        confirmLoading={submitLoading}
        onOk={this.handleSubmit}
        onCancel={this.handleCancel}
      >
        <Form hideRequiredMark className="tableListForm">
          <Row gutter={12}>
            {this.renderInputInfoElem()}
          </Row>
        </Form>
      </Modal>
    );
  }
}

export default Form.create<RechargeInfoProps>()(RechargeInfoElem);
